﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;
using RotovapPlatform.Domain.Equipment.DeviceParameters;

namespace RotovapPlatform.UI.ViewModels.DeviceMaintenance
{
	/// <summary>
	/// 设备参数编辑视图模型
	/// </summary>
	public partial class DeviceParameterViewModel : ObservableObject
	{
		private readonly IDeviceParameterService _parameterService;
		private DeviceParametersEntity _parameters;
		private Motor _selectedMotor;
		private Pump _selectedPump;
		private Sensor _selectedSensor;
		private string _selectedProcessParameterKey;
		private string _statusMessage;

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="parameterService">设备参数服务</param>
		public DeviceParameterViewModel(IDeviceParameterService parameterService)
		{
			_parameterService = parameterService;

			// 初始化命令
			LoadParametersCommand = new AsyncRelayCommand(LoadParametersAsync);
			SaveParametersCommand = new AsyncRelayCommand(SaveParametersAsync, () => Parameters != null);
			ResetToDefaultCommand = new AsyncRelayCommand(ResetToDefaultAsync);
			ExportParametersCommand = new AsyncRelayCommand(ExportParameters);
			ImportParametersCommand = new AsyncRelayCommand(ImportParameters);
			UseDefaultParametersCommand = new AsyncRelayCommand(UseDefaultParametersAsync);

			// 加载参数
			_ = LoadParametersAsync();
		}

		/// <summary>
		/// 设备参数
		/// </summary>
		public DeviceParametersEntity Parameters
		{
			get => _parameters;
			set
			{
				if (SetProperty(ref _parameters, value))
				{
					OnPropertyChanged(nameof(ProcessParameterKeys));
					OnPropertyChanged(nameof(Motors));
					OnPropertyChanged(nameof(Sensors));
				}
			}
		}

		/// <summary>
		/// 工艺参数键列表
		/// </summary>
		public IEnumerable<string> ProcessParameterKeys => Parameters?.ProcessParameters.Keys;

		/// <summary>
		/// 电机列表
		/// </summary>
		public ObservableCollection<Motor> Motors
		{
			get => Parameters?.Motors != null ? new ObservableCollection<Motor>(Parameters.Motors) : null;
		}

		/// <summary>
		/// 传感器列表
		/// </summary>
		public ObservableCollection<Sensor> Sensors
		{
			get => Parameters?.Sensors != null ? new ObservableCollection<Sensor>(Parameters.Sensors) : null;
		}

		/// <summary>
		/// 选中的电机
		/// </summary>
		public Motor SelectedMotor
		{
			get => _selectedMotor;
			set => SetProperty(ref _selectedMotor, value);
		}

		/// <summary>
		/// 选中的传感器
		/// </summary>
		public Sensor SelectedSensor
		{
			get => _selectedSensor;
			set => SetProperty(ref _selectedSensor, value);
		}

		/// <summary>
		/// 选中的工艺参数键
		/// </summary>
		public string SelectedProcessParameterKey
		{
			get => _selectedProcessParameterKey;
			set
			{
				if (SetProperty(ref _selectedProcessParameterKey, value))
				{
					OnPropertyChanged(nameof(SelectedProcessParameter));
				}
			}
		}

		/// <summary>
		/// 选中的工艺参数
		/// </summary>
		public ProcessParameter SelectedProcessParameter
		{
			get => Parameters?.ProcessParameters.TryGetValue(SelectedProcessParameterKey, out var parameter) == true ? parameter : null;
		}


		/// <summary>
		/// 状态消息
		/// </summary>
		public string StatusMessage
		{
			get => _statusMessage;
			set => SetProperty(ref _statusMessage, value);
		}

		/// <summary>
		/// 加载参数命令
		/// </summary>
		public IAsyncRelayCommand LoadParametersCommand { get; }

		/// <summary>
		/// 保存参数命令
		/// </summary>
		public IAsyncRelayCommand SaveParametersCommand { get; }

		/// <summary>
		/// 重置为默认参数命令
		/// </summary>
		public IAsyncRelayCommand ResetToDefaultCommand { get; }

		/// <summary>
		/// 导出参数命令
		/// </summary>
		public IAsyncRelayCommand ExportParametersCommand { get; }

		/// <summary>
		/// 导入参数命令
		/// </summary>
		public IAsyncRelayCommand ImportParametersCommand { get; }

		/// <summary>
		/// 使用默认参数命令
		/// </summary>
		public IAsyncRelayCommand UseDefaultParametersCommand { get; }

		/// <summary>
		/// 加载参数
		/// </summary>
		private async Task LoadParametersAsync()
		{
			try
			{
				StatusMessage = "正在加载设备参数...";

				// 清除服务中的缓存参数，确保从文件重新加载
				await _parameterService.ClearCacheAsync();

				// 加载参数
				Parameters = await _parameterService.GetParametersAsync();

				if (Parameters.Motors.Count > 0)
				{
					SelectedMotor = Parameters.Motors[0];
				}

				if (Parameters.Sensors.Count > 0)
				{
					SelectedSensor = Parameters.Sensors[0];
				}

				if (Parameters.ProcessParameters.Count > 0)
				{
					SelectedProcessParameterKey = Parameters.ProcessParameters.Keys.First();
				}

				StatusMessage = "设备参数加载成功";
			}
			catch (Exception ex)
			{
				StatusMessage = $"加载设备参数失败: {ex.Message}";
				MessageBox.Show($"加载设备参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			finally
			{

			}
		}

		/// <summary>
		/// 保存参数
		/// </summary>
		private async Task SaveParametersAsync()
		{
			try
			{
				StatusMessage = "正在保存设备参数...";

				var result = await _parameterService.SaveParametersAsync(Parameters);

				if (result.Success)
				{
					StatusMessage = "设备参数保存成功，电机参数将在系统中自动更新";
					MessageBox.Show("设备参数保存成功，电机参数将在系统中自动更新", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
				}
				else
				{
					StatusMessage = $"设备参数保存失败: {result.Message}";
					MessageBox.Show($"设备参数保存失败: {result.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
				}
			}
			catch (Exception ex)
			{
				StatusMessage = $"保存设备参数失败: {ex.Message}";
				MessageBox.Show($"保存设备参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			finally
			{

			}
		}

		/// <summary>
		/// 重置为默认参数
		/// </summary>
		private async Task ResetToDefaultAsync()
		{
			try
			{
				var result = MessageBox.Show("确定要重置为默认参数吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

				if (result != MessageBoxResult.Yes)
				{
					return;
				}

			
				StatusMessage = "正在重置为默认参数...";

				var operationResult = await _parameterService.ResetToDefaultAsync();

				if (operationResult.Success)
				{
					await LoadParametersAsync();
					StatusMessage = "重置为默认参数成功，电机参数将在系统中自动更新";
					MessageBox.Show("重置为默认参数成功，电机参数将在系统中自动更新", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
				}
				else
				{
					StatusMessage = $"重置为默认参数失败: {operationResult.Message}";
					MessageBox.Show($"重置为默认参数失败: {operationResult.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
				}
			}
			catch (Exception ex)
			{
				StatusMessage = $"重置为默认参数失败: {ex.Message}";
				MessageBox.Show($"重置为默认参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			finally
			{
				
			}
		}

		/// <summary>
		/// 导出参数
		/// </summary>
		private async Task ExportParameters()
		{
			try
			{
				var dialog = new SaveFileDialog
				{
					Filter = "JSON文件|*.json",
					Title = "导出设备参数",
					FileName = "deviceParameters.json"
				};

				if (dialog.ShowDialog() == true)
				{
			
					StatusMessage = "正在导出设备参数...";

					// 使用异步方式调用导出功能
					var result = await _parameterService.ExportParametersAsync(dialog.FileName);

					if (result)
					{
						StatusMessage = $"设备参数导出成功: {dialog.FileName}";
						MessageBox.Show($"设备参数导出成功: {dialog.FileName}", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
					}
					else
					{
						StatusMessage = "设备参数导出失败";
						MessageBox.Show("设备参数导出失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
					}
				}
			}
			catch (Exception ex)
			{
				StatusMessage = $"导出设备参数失败: {ex.Message}";
				MessageBox.Show($"导出设备参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			finally
			{
			
			}
		}

		/// <summary>
		/// 导入参数
		/// </summary>
		private async Task ImportParameters()
		{
			try
			{
				var dialog = new OpenFileDialog
				{
					Filter = "JSON文件|*.json",
					Title = "导入设备参数"
				};

				if (dialog.ShowDialog() == true)
				{
					var result = MessageBox.Show("导入参数将覆盖当前参数，确定要继续吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

					if (result != MessageBoxResult.Yes)
					{
						return;
					}

				
					StatusMessage = "正在导入设备参数...";

					// 使用异步方式调用导入功能
					var success = await _parameterService.ImportParametersAsync(dialog.FileName);

					if (success)
					{
						await LoadParametersAsync();
						StatusMessage = $"设备参数导入成功: {dialog.FileName}";
						MessageBox.Show($"设备参数导入成功: {dialog.FileName}", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
					}
					else
					{
						StatusMessage = "设备参数导入失败";
						MessageBox.Show("设备参数导入失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
					}
				}
			}
			catch (Exception ex)
			{
				StatusMessage = $"导入设备参数失败: {ex.Message}";
				MessageBox.Show($"导入设备参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			finally
			{
			
			}
		}

		/// <summary>
		/// 使用默认参数
		/// </summary>
		private async Task UseDefaultParametersAsync()
		{
			try
			{
				var result = MessageBox.Show("确定要使用默认参数吗？这将直接加载默认参数文件中的内容。", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

				if (result != MessageBoxResult.Yes)
				{
					return;
				}

				
				StatusMessage = "正在加载默认参数...";

				// 直接从默认配置文件加载参数
				var defaultConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "defaultDeviceParameters.json");
				if (File.Exists(defaultConfigPath))
				{
					try
					{
						var json = await File.ReadAllTextAsync(defaultConfigPath);
						var jsonOptions = new JsonSerializerOptions
						{
							PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
							AllowTrailingCommas = true,
							ReadCommentHandling = JsonCommentHandling.Skip
						};
						Parameters = JsonSerializer.Deserialize<DeviceParametersEntity>(json, jsonOptions);

						// 保存到当前配置文件
						var result1 = await _parameterService.SaveParametersAsync(Parameters);

						if (result1.Success)
						{
							StatusMessage = "默认参数加载成功";
							MessageBox.Show("默认参数加载成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
						}
						else
						{
							StatusMessage = "保存默认参数失败";
							MessageBox.Show("保存默认参数失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
						}
					}
					catch (Exception ex)
					{
						StatusMessage = $"加载默认参数失败: {ex.Message}";
						MessageBox.Show($"加载默认参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
					}
				}
				else
				{
					StatusMessage = "默认参数文件不存在";
					MessageBox.Show("默认参数文件不存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
				}
			}
			catch (Exception ex)
			{
				StatusMessage = $"使用默认参数失败: {ex.Message}";
				MessageBox.Show($"使用默认参数失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			finally
			{
				
			}
		}
	}
}